from django.views import View

from User.models import Order
from sportsground.utils import Req
from sportsground.utils.Res import Res
from sportsground.utils.views import LoginRequiredUser


class OrderView(LoginRequiredUser, View):
    """ 订单信息 """

    def get(self, request):
        """ 查询 """
        user = request.user.user
        page = int(request.GET.get('page',1))
        number = int(request.GET.get('number',5))

        result = []
        orders = Order.objects.filter(user=user).order_by('-oid')
        pageInfo = {
            "count": orders.count(),
            "page": page,
            "number": number
        }

        for order in orders[number*(page-1):number*(page)]:
            result.append(order.Info())
        return Res.Json(Res.OK, result=result, page=pageInfo)

    @Req.getJson
    def post(self, request):
        """ 退款 """
        oid = request.json_dict.get('oid')
        id = request.json_dict.get('id')
        message = request.json_dict.get('message', '')

        user = request.user.user

        order = Order.objects.filter(oid=oid, user=user).first()
        if not order:
            return Res.Json(Res.Warn)

        state, msg = order.drawback(id, message)
        if state:
            return Res.Json(Res.OK)
        else:
            return Res.Json(Res.Warn, msg=msg)
